package com.hnyfkj.jyindustry.common.validator;

import com.hnyfkj.jyindustry.common.exception.HnyfkjBusinessException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * @author zl
 *
 *
 * @date 2020-04-22 10:50
 */
public class ValidatorUtils {
    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     *
     * @param object 待校验对象
     * @param groups 待校验的组
     * @throws BusinessException 校验不通过，则报BusinessException异常
     */
    public static void validateEntity(final Object object, final Class<?>... groups) throws HnyfkjBusinessException {
        final Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            final ConstraintViolation<Object> constraint = constraintViolations.iterator().next();
            throw new HnyfkjBusinessException(constraint.getMessage(), 400);
        }
    }
}
